package com.easy.generator;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * @author easy
 * @date 2025年07月05日 10:56
 */
public class MapperGenerator  {


        public static void generate() throws Exception {
            // 获取类加载器
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            // 扫描包下的所有类
            Set<Class<?>> classes = scanClasses(Easy.BEAN_PACKAGE, classLoader);
            // 为每个实体类生成Controller
            for (Class<?> clazz : classes) {
                if (isEntityClass(clazz)) {
                    generateMapperFile(clazz);
                }
            }
            generateMapperConfig();
        }

    private static void generateMapperConfig() throws IOException {
        String fileName =  "MyBatisPlusConfig";
        File dir = new File(Easy.PROJECT_ABSOLUTE_URL+"/src/main/java/" + Easy.CONFIG_PACKAGE.replace('.', '/'));
        if (!dir.exists()) {
            dir.mkdirs();}

        File file = new File(dir, fileName + ".java");
        try (PrintWriter out = new PrintWriter(file)) {
            String content="package "+Easy.CONFIG_PACKAGE+";\n" +
                    "\n" +
                    "import com.baomidou.mybatisplus.annotation.DbType;\n" +
                    "import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;\n" +
                    "import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;\n" +
                    "import org.springframework.context.annotation.Bean;\n" +
                    "import org.springframework.context.annotation.Configuration;\n" +
                    "\n" +
                    "@Configuration\n" +
                    "public class "+fileName+" {\n" +
                    "    @Bean\n" +
                    "    public MybatisPlusInterceptor mybatisPlusInterceptor() {\n" +
                    "        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();\n" +
                    "        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); \n" +
                    "        return interceptor;\n" +
                    "    }\n" +
                    "}\n" ;
            out.println(content);
        }
    }

        private static Set<Class<?>> scanClasses(String packageName, ClassLoader classLoader) throws Exception {
            Set<Class<?>> classes = new HashSet<>();
            String path = packageName.replace('.', '/');
            Enumeration<URL> resources = classLoader.getResources(path);

            while (resources.hasMoreElements()) {
                URL resource = resources.nextElement();
                if (resource.getProtocol().equals("file")) {
                    classes.addAll(findClasses(new File(resource.getFile()), packageName));
                }
            }
            return classes;
        }

        private static Set<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
            Set<Class<?>> classes = new HashSet<>();
            if (!directory.exists()) return classes;

            File[] files = directory.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    classes.addAll(findClasses(file, packageName + "." + file.getName()));
                } else if (file.getName().endsWith(".class")) {
                    String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
                    classes.add(Class.forName(className));
                }
            }
            return classes;
        }

        private static boolean isEntityClass(Class<?> clazz) {
            // 简单的实体类判断逻辑，可根据实际需求扩展
            return !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers());
        }

        private static void generateMapperFile(Class<?> entityClass) throws IOException {
            String className = entityClass.getSimpleName();
            String FileName = className + "Mapper";
            File dir = new File(Easy.PROJECT_ABSOLUTE_URL+"/src/main/java/" + Easy.MAPPER_PACKAGE.replace('.', '/'));
            if (!dir.exists()) {
                dir.mkdirs();}

            File file = new File(dir, FileName + ".java");
            try (PrintWriter out = new PrintWriter(file)) {
                String content="package "+Easy.MAPPER_PACKAGE+";\n" +
                        "\n" +
                        "import com.baomidou.mybatisplus.core.mapper.BaseMapper;\n" +
                        "import org.apache.ibatis.annotations.Mapper;\n" +
                        "import "+Easy.BEAN_PACKAGE+"."+className+";\n" +
                        "\n" +
                        "@Mapper\n" +
                        "public interface "+className+"Mapper extends BaseMapper<"+className+"> {\n" +
                        "}\n";

                out.println(content);

            }
        }
}
